package com.example.mediaclient;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private MediaBrowserCompat mediaBrowser;
    private MediaControllerCompat mediaController;

    // UI 元素
    private ImageView albumArt;
    private TextView songTitle;
    private TextView songArtist;
    private TextView currentTime;
    private TextView totalTime;
    private SeekBar progressSeekbar;
    private ImageButton btnPrevious;
    private ImageButton btnPlayPause;
    private ImageButton btnNext;
    private TextView serviceStatus;
    private static final int PERMISSION_REQUEST_CODE = 100;
    private Handler handler = new Handler();
    private Runnable updateProgressRunnable = new Runnable() {
        @Override
        public void run() {
            updateProgress();
            // 只有在连接状态下才继续更新
            if (mediaController != null) {
                handler.postDelayed(this, 1000); // 每秒更新一次
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkAndRequestPermissions();
        initViews();
        setupMediaBrowser();
        setupClickListeners();
    }
    private void checkAndRequestPermissions() {
        Toast.makeText(this, "正在检查权限...", Toast.LENGTH_SHORT).show();

        // 根据 Android 版本使用不同的权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                showPermissionExplanationIfNeeded(Manifest.permission.READ_MEDIA_AUDIO);
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_MEDIA_AUDIO},
                        PERMISSION_REQUEST_CODE);
            }
        } else {
            // Android 12 及以下
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                showPermissionExplanationIfNeeded(Manifest.permission.READ_EXTERNAL_STORAGE);
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        PERMISSION_REQUEST_CODE);
            }
        }
    }
    private void showPermissionExplanationIfNeeded(String permission) {
        Toast.makeText(this, "正在获取权限...", Toast.LENGTH_SHORT).show();
        // 检查是否需要显示权限说明
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            Toast.makeText(this, "需要存储权限来访问您的音乐文件", Toast.LENGTH_LONG).show();
            Log.d("Permission", "Showing permission rationale");
        } else {
            Log.d("Permission", "No need to show rationale");
        }
    }

    private void initViews() {
        albumArt = findViewById(R.id.album_art);
        songTitle = findViewById(R.id.song_title);
        songArtist = findViewById(R.id.song_artist);
        currentTime = findViewById(R.id.current_time);
        totalTime = findViewById(R.id.total_time);
        progressSeekbar = findViewById(R.id.progress_seekbar);
        btnPrevious = findViewById(R.id.btn_previous);
        btnPlayPause = findViewById(R.id.btn_play_pause);
        btnNext = findViewById(R.id.btn_next);
        serviceStatus = findViewById(R.id.service_status);

        // 设置进度条监听器
        progressSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaController != null) {
                    // 用户拖动SeekBar时更新时间显示
                    currentTime.setText(formatTime(progress));
//                    mediaController.getTransportControls().seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖动时跳转到指定位置
                if (mediaController != null) {
                    mediaController.getTransportControls().seekTo(seekBar.getProgress());
                }
            }
        });
    }
    /**
     * 初始化媒体浏览器连接
     * 创建一个新的MediaBrowserCompat实例用于与媒体服务进行通信。
     * 该方法设置必要的连接参数包括当前上下文、媒体服务组件、连接回调等。
     */
    private void setupMediaBrowser() {
        mediaBrowser = new MediaBrowserCompat(
                this,
                new ComponentName("com.example.mediaservice", "com.example.mediaservice.MediaService"),
                connectionCallback,
                null
        );
    }
//    设置播放/暂停按钮的点击监听器
    private void setupClickListeners() {
        btnPlayPause.setOnClickListener(v -> {
            if (mediaController != null) {
                PlaybackStateCompat currentState = mediaController.getPlaybackState();
                if (currentState != null) {
                    switch (currentState.getState()) {
                        case PlaybackStateCompat.STATE_PLAYING:
                            mediaController.getTransportControls().pause();
                            break;
                        case PlaybackStateCompat.STATE_PAUSED:
                        case PlaybackStateCompat.STATE_STOPPED:
                            mediaController.getTransportControls().play();
                            break;
                        default:
                            mediaController.getTransportControls().play();
                            break;
                    }
                }
            }
        });

        btnPrevious.setOnClickListener(v -> {
            if (mediaController != null) {
                mediaController.getTransportControls().skipToPrevious();
            }
        });

        btnNext.setOnClickListener(v -> {
            if (mediaController != null) {
                mediaController.getTransportControls().skipToNext();
            }
        });
        albumArt.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.example.mediaservice", "com.example.mediaservice.MainActivity"));
            startActivity(intent);
        });
    }
    /**
     * MediaBrowserCompat的连接回调接口实现，用于处理与媒体浏览器服务的连接状态变化
     * 该回调包含三个核心方法：
     * - onConnected(): 当成功连接到媒体服务时调用
     * - onConnectionSuspended(): 当连接被暂停时调用
     * - onConnectionFailed(): 当连接失败时调用
     */
    private final MediaBrowserCompat.ConnectionCallback connectionCallback =
            new MediaBrowserCompat.ConnectionCallback() {
                @Override
                public void onConnected() {
                    Log.d(TAG, "MediaBrowser connected");
                    try {
                        // 创建 MediaController
                        mediaController = new MediaControllerCompat(
                                MainActivity.this,
                                mediaBrowser.getSessionToken()
                        );

                        // 将 MediaController 与 Activity 关联
                        MediaControllerCompat.setMediaController(MainActivity.this, mediaController);

                        // 注册回调以接收媒体状态更新
                        mediaController.registerCallback(mediaControllerCallback);

                        // 更新 UI 状态
                        runOnUiThread(() -> {
                            serviceStatus.setText("服务已连接");
                            updateMediaMetadata(mediaController.getMetadata());
                            updatePlaybackStateUI(mediaController.getPlaybackState());
                        });

                        // 开始更新进度
                        handler.post(updateProgressRunnable);

                    } catch (Exception e) {
                        Log.e(TAG, "Failed to create MediaController", e);
                    }
                }

                @Override
                public void onConnectionSuspended() {
                    Log.d(TAG, "MediaBrowser connection suspended");
                    runOnUiThread(() -> serviceStatus.setText("服务连接已暂停"));
                }

                @Override
                public void onConnectionFailed() {
                    Log.e(TAG, "MediaBrowser connection failed");
                    runOnUiThread(() -> serviceStatus.setText("服务连接失败"));
                    Toast.makeText(MainActivity.this, "无法连接到媒体服务", Toast.LENGTH_SHORT).show();
                }
            };

    //媒体控制器回调对象，用于监听媒体播放状态和元数据的变化
    private final MediaControllerCompat.Callback mediaControllerCallback =
            new MediaControllerCompat.Callback() {
                @Override
                public void onPlaybackStateChanged(PlaybackStateCompat state) {
                    Log.d(TAG, "Playback state changed: " + state);
                    runOnUiThread(() -> updatePlaybackStateUI(state));
                }

                @Override
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    Log.d(TAG, "Metadata changed: " + metadata);
                    runOnUiThread(() -> updateMediaMetadata(metadata));
                }
            };

    //    更新播放状态UI
    private void updatePlaybackStateUI(PlaybackStateCompat state) {
        if (state == null) return;

        // 更新播放/暂停按钮
        switch (state.getState()) {
            case PlaybackStateCompat.STATE_PLAYING:
                btnPlayPause.setImageResource(android.R.drawable.ic_media_pause);
                break;
            case PlaybackStateCompat.STATE_PAUSED:
            case PlaybackStateCompat.STATE_STOPPED:
                btnPlayPause.setImageResource(android.R.drawable.ic_media_play);
                break;
        }

        // 更新进度条
        updateProgress();
    }

    //更新媒体元数据信息
    private void updateMediaMetadata(MediaMetadataCompat metadata) {
        if (metadata == null) return;

        // 更新歌曲信息
        String title = metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
        String artist = metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
        long duration = metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);

        songTitle.setText(title != null ? title : "未知歌曲");
        songArtist.setText(artist != null ? artist : "未知艺术家");
        totalTime.setText(formatTime(duration));
        progressSeekbar.setMax((int) duration);
    }

    private void updateProgress() {
        if (mediaController != null) {
            PlaybackStateCompat state = mediaController.getPlaybackState();
            if (state != null) {
                long currentPosition = state.getPosition();
                currentTime.setText(formatTime(currentPosition));
                progressSeekbar.setProgress((int) currentPosition);
            }
        }
    }

    private String formatTime(long milliseconds) {
        long seconds = milliseconds / 1000;
        long minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "Connecting to MediaBrowser");
        mediaBrowser.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "Disconnecting from MediaBrowser");

        // 停止更新进度
        handler.removeCallbacks(updateProgressRunnable);

        // 注销回调
        if (mediaController != null) {
            mediaController.getTransportControls().stop();
            mediaController.unregisterCallback(mediaControllerCallback);
            mediaController = null;
        }

        mediaBrowser.disconnect();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
